angular.module('project', [])
	.config(function($routeProvider) {
		$routeProvider.when('/', {
			controller : ListCtrl,
			templateUrl : 'list.html'
		}).when('/edit/:id', {
			controller : EditCtrl,
			templateUrl : 'file.html'
		}).when('/new', {
			controller : CreateCtrl,
			templateUrl : 'file.html'
		}).otherwise({
			redirectTo : '/'
		});
	}).config(['$httpProvider', function($httpProvider) {
		$httpProvider.defaults.useXDomain = true;
		delete $httpProvider.defaults.headers.common['X-Requested-With'];
	}])
	.directive('ckEditor', function() {
		return {
			require: '?ngModel',
			link: function(scope, elm, attr, ngModel) {
				var ck = CKEDITOR.replace(elm[0], {
					height: '250px'
				});
				if (!ngModel) return;
				//I added this because sometimes $render would call setData before the ckeditor was ready
				ck.on('instanceReady', function() {
					ck.setData(ngModel.$viewValue);
				});
				ck.on('pasteState', function() {
					scope.$apply(function() {
						ngModel.$setViewValue(ck.getData());
					});
				});
				ngModel.$render = function(value) {
					ck.setData(ngModel.$viewValue);
				};
			}
		};
	});

var API_URL = 'https://7inpham.appspot.com/_ah/api/bapi/v1';

function ListCtrl($scope, $http) {
	$scope.projects = [];
	$http({
		method : 'GET',
		url : API_URL + '/blogpost?limit=0'
	}).success(function(data, status, headers, config) {
		angular.forEach(data.items, function(item) {
			$scope.projects.push(item);
		});
	}).error(function(data, status, headers, config) {
		console.log("Error");
	});
}

function CreateCtrl($scope, $http, $location) {
	$scope.save = function() {
		$http({
			method : 'POST',
			url : API_URL + '/blogpost',
			data : $scope.project
		}).success(function(data, status, headers, config) {
			alert("Posted");
			$location.path('/');
		}).error(function(data, status, headers, config) {
			alert("Error");
		});
	}
}

function EditCtrl($scope, $http, $location, $routeParams) {
	$http({
		method : 'GET',
		url : API_URL + '/blogpost/' + $routeParams.id
	}).success(function(data, status, headers, config) {
		$scope.project = data;
	}).error(function(data, status, headers, config) {
		console.log("Error");
	});
	$scope.remove = function() {
		alert("This action is not allowed now.");
		/*
		$http({
			method : 'DELETE',
			url : API_URL + '/blogpost/' + $scope.project.id
		}).success(function(data, status, headers, config) {
			$location.path('/');
		}).error(function(data, status, headers, config) {
			$location.path('/');
		});
		*/
	};
	$scope.save = function() {
		$http({
			method : 'PUT',
			url : API_URL + '/blogpost/' + $scope.project.id,
			data : $scope.project
		}).success(function(data, status, headers, config) {
			alert("Updated");
		}).error(function(data, status, headers, config) {
			alert("Error");
		});
	};
}